#!/usr/bin/env python
# coding=utf-8
import pygame
import sys

from bullet import Bullet


def check_keydown_events(event, ai_settings, screen, ship, bullets):
    if event.key == pygame.K_RIGHT:
        print("开始按right")
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        print("开始按left")
        ship.moving_left = True
    elif event.key == pygame.K_UP:
        print("开始按up")
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        print("开始按down")
        ship.moving_down = True
    elif event.key == pygame.K_SPACE:
        print("开始按pause")
        fire_bullet(ai_settings, screen, ship, bullets)


def check_keyup_events(event, ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False


def check_events(ai_settings, screen, ship, bullets):
    """
    响应按键和鼠标事件
    :return:
    """
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets)

        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)


def update_screen(ai_settings, screen, ship, bullets):
    """
    更新屏幕上的图像，并切换到新的屏幕
    :param bullets:
    :param ai_settings:
    :param screen:
    :param ship:
    :return:
    """
    screen.fill(ai_settings.bg_color)

    for bullet in bullets:
        bullet.draw_bullet()
    ship.blitme()
    pygame.display.flip()


def update_bullets(bullets):
    """
    发射子弹
    """
    bullets.update()
    # 删除已消失的子弹
    for bullet in bullets.copy():
        if bullet.rect.top <= 0:
            bullets.remove(bullet)


def fire_bullet(ai_settings, screen, ship, bullets):
    """
    如果么有达到上限，就发射一颗子弹
    """
    if len(bullets) < ai_settings.bullet_allowed:
        new_bullet = Bullet(ai_settings, ship, screen)
        bullets.add(new_bullet)
